#include "../include/TcpServer.h"
#include <iostream>
#include <string>

using PtrConnection = std::shared_ptr<Connection>;
static NetWork nw;
class EchoServer
{
public:
    EchoServer(uint16_t port)
        : _server(port)
    {
        _server.setThreadCount(4);
        _server.EnableInactiveRelease(10);
        _server.SetConnectedCallBack(std::bind(&EchoServer::OnConnection, this, std::placeholders::_1));
        _server.SetMessageCallBack(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
        _server.SetClosedCallBack(std::bind(&EchoServer::OnClose, this, std::placeholders::_1));
    }

    void Start()
    {
        _server.Start();
    }

private:
    void OnConnection(const PtrConnection &conn)
    {
        if (conn->getConnected())
        {
            DBG_LOG("New connection %lu (fd %d) established.", conn->getId(), conn->getFd());
            DBG_LOG("Enabled 10s inactivity timer for connection %lu.", conn->getId());
        }
    }

    void OnMessage(const PtrConnection &conn, Buffer *buffer)
    {
        size_t readable = buffer->ReadableSpace();
        DBG_LOG("Message from connection %lu (fd %d): echoing %lu bytes.", conn->getId(), conn->getFd(), readable);
        // Echo the received data back to the client
        std::string msg = buffer->ReadAsStringAndPop(readable);
        conn->Send(msg.c_str(), msg.length());
    }

    void OnClose(const PtrConnection &conn)
    {
        DBG_LOG("Connection %lu from fd %d closed.", conn->getId(), conn->getFd());
    }

private:
    TcpServer _server;
};

int main()
{

    EchoServer server(8500);

    std::cout << "Server started, listening on port 8500..." << std::endl;
    server.Start(); // This will block

    return 0;
}
